import { message } from 'antd';
import { queryRegionNetworks, createRegionNetwork,
  updateRegionNetwork, removeRegionNetwork,
  getRegionNetwork } from '../services/regionnetworks';

export default {
  namespace: 'regionnetwork',
  state: {
    data: {
      list: [],
      pagination: {},
    },
    loading: true,
    queryInfo: {},
  },
  effects: {
    *fetch({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const res = yield call(queryRegionNetworks, payload);
      yield put({
        type: 'save',
        payload: res,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
    *add({ payload }, { call, put }) {
      const { id, createTime, updateTime, ...restParams } = payload;
      yield call(createRegionNetwork, restParams);
      message.success('添加成功');
      yield put({ type: 'fetch' });
    },
    *update({ payload }, { call, put }) {
      const { createTime, updateTime, ...restParams } = payload;
      yield call(updateRegionNetwork, restParams);
      message.success('Update成功');
      yield put({ type: 'fetch' });
    },
    *delete({ payload }, { call, put }) {
      yield call(removeRegionNetwork, payload);
      message.success('Delete成功');
      yield put({ type: 'fetch' });
    },
    *batchRemove({ payload }, { call, put }) {
      for (let i = 0; i < payload.length; i++) {
        yield call(removeRegionNetwork, payload[i]);
      }
      message.success('Delete成功');
      yield put({ type: 'fetch' });
    },
    *query({ payload }, { put, call }) {
      const rest = yield call(getRegionNetwork, payload);
      yield put({
        type: 'saveOne',
        payload: rest,
      });
    },
  },
  reducers: {
    save(state, { payload }) {
      const { page, _embedded } = payload;
      return {
        ...state,
        data: {
          list: _embedded.regionNetworks,
          pagination: {
            pageSize: page.size,
            total: page.totalElements,
            current: page.number + 1,
          },
        },
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
    saveOne(state, { payload }) {
      return {
        ...state,
        queryInfo: payload,
      };
    },
  },
};
